package cc.telecomdigital.tdstock.activity.groups.stock;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import cc.mango.android.chart.StkTimeView;
import cc.mango.common.FinalKey;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.WebViewHelper;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.CONNECT_TYPE;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.INetworkChangeListener;
import cc.telecomdigital.tdstock.Framework.UniqueItem.ScreenOrientationChangeListener.IScreenOrientationChangeListener;
import cc.telecomdigital.tdstock.Framework.UniqueItem.ScreenOrientationChangeListener.SCR_ORIENTATION;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.AboutActivity;
import cc.telecomdigital.tdstock.activity.BMPBaseActivity;
import cc.telecomdigital.tdstock.activity.chart.StkChartActivity;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.activity.groups.more.StockStarIndexActivity;
import cc.telecomdigital.tdstock.model.StockInfo;
import cc.telecomdigital.tdstock.trading.Trade_LoginActivity;
import cc.telecomdigital.tdstock.trading.Trade_OrderKeypadActivity;
import cc.telecomdigital.tdstock.trading.Trade_tradingOptionActivity;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.utils.Futures;
import cc.telecomdigital.tdstock.utils.Index;
import cc.telecomdigital.tdstock.utils.Stock;
import cc.telecomdigital.tdstock.utils.WorldIndex;

/**
 * BMP StockInfo Activity
 * 
 * @author ouyangzhihui
 */
public class BMPCurrentStockInfoActivity extends BMPBaseActivity implements
	IScreenOrientationChangeListener, OnEditorActionListener,
	INetworkChangeListener
{
	private String				TAG				= "BMPCurrentStockInfoActivity";

	private static NumberFormat	_formaterOnSacle2;
	private static NumberFormat	_formaterOnSacle1;

	private static Button		_toolbutton_backWarrantResult;

	// final private String index_itemCodeStr = "HSI,HSCEI";
	// final private String futures_itemCodeStr = "HSI:1,HSI:2";
	// final private String worldIndexSSEI_itemCodeStr = "SSE1";
	final private String[]		index_itemCode		= { "HSI", "HSCEI" };
	final private String[]		futures_itemCode	= { "HSI:1", "HSI:2" };
	// final private String[] worldIndexSSEI_itemCode = {"SSE1"};

	public static String		_stockCode;
	public static String		_lastStockCode		= "1";
	// public static boolean _isNewStock = false;

	private TextView			_index_hsi;
	private TextView			_index_his_net;
	private TextView			_index_his_turnover;

	private TextView			_index_phsi;
	private TextView			_index_phsi_net;

	private TextView			_index_futures_hsi_1;
	private TextView			_index_futures_hsi_1_net;

	private TextView			_index_futures_hsi_2;
	private TextView			_index_futures_hsi_2_net;

	private TextView			_worldindex_sse1;
	private TextView			_worldindex_sse1_net;

	private TextView			_server_time;

	private EditText			_current_stock_code;
	private TextView			_current_stock_chinese_short_name;
	private TextView			_current_stock_nominal;

	private ImageView			_up_down;
	private TextView			_current_stock_net;
	private TextView			_current_stock_net_percentage;

	private TextView			_current_stock_sharetraded;
	private TextView			_current_stock_turnover;
	private TextView			_current_stock_prevcloseprice;
	private TextView			_current_stock_openprice;
	private TextView			_current_stock_highprice;
	private TextView			_current_stock_lowprice;

	private TextView			_current_stock_lotsize;
	private TextView			_current_stock_ex_ymd;
	private TextView			_current_stock_year_high;
	private TextView			_current_stock_div_ymd;

	private TextView			_current_stock_year_low;
	private TextView			_current_stock_div_value;
	private TextView			_current_stock_profitpershare;
	private TextView			_current_stock_rate_of_return;

	private TextView			_current_stock_currency;
	private TextView			_current_stock_pe;
	private TextView			_current_stock_day_10_avg;

	private TextView			_current_stock_rsi9;
	private TextView			_current_stock_day_20_avg;
	private TextView			_current_stock_rsi14;
	private TextView			_current_stock_day_50_avg;

	private TextView			_current_stock_day_100_avg;
	private TextView			_current_stock_day_200_avg;
	private TextView			_current_stock_day_250_avg;

	private TextView			_chart_mask;
	private StkTimeView			_stkTimeView;

	private SharedPreferences	_prefsStockCode;

	private CustomizeDialog		_entryErrordialog;

	private boolean			_isWarrant;
	private TableRow			_rowForWarrant;
	private String[][]			_res4ReplaceMent;
	private TextView[]			_label4ReplaceMent;
	private TextView[]			_field_value_4ReplaceMent;

	private TextView			_field_current_stock_call_put;
	private TextView			_field_current_stock_gearing;

	private ScrollView			_scrollview;

	private Animation			anim_down			= null;
	private Animation			anim_up			= null;

	public LinearLayout			container_input;
	private TextView			editTextView;

	private void dealwithEnterCode(int number)
	{
		String tmp = _current_stock_code.getText().toString();
		switch (number)
		{
			case 10: // ok
				if (tmp.length() > 0)
				{
					_current_stock_code.setText(String.valueOf(Integer
							.parseInt(tmp, 10)));
					_current_stock_code.clearFocus();
				}
				container_input.startAnimation(anim_up);
				// If there is no network, create a prompt
				if (!SystemInfo.isNetworkingConnected(this))
				{
					new CustomizeDialog(
							getMyOwnContext(),
							getResources().getString(R.string.info),
							getResources()
									.getString(
											R.string.networking_disconnect_tips))
					{
						@Override
						public void onClick(View v)
						{
							if (v == okButton)
							{
								dismiss();
								_current_stock_code
										.setText(lastStockCode);
								// _current_stock_code.setSelection(_current_stock_code.getText().toString().length());
								_current_stock_code.clearFocus();
							}
						}
					}.show();
				}
				else
				{
					// startSunFlowBuy();
					_toolbutton_backWarrantResult.setVisibility(View.GONE); // by
																	// ouyangzhihui
																	// 2011-06-28
					dealWithNewStockCodeComingFromEditor();
				}
				break;
			case -1: // del
				if (tmp.length() > 0)
					_current_stock_code.setText(tmp.subSequence(0,
							tmp.length() - 1));
				_current_stock_code.requestFocus();
				_current_stock_code.setSelection(_current_stock_code
						.getText().toString().length());
				break;
			default:
				_current_stock_code.setText(tmp + number);
				_current_stock_code.requestFocus();
				_current_stock_code.setSelection(_current_stock_code
						.getText().toString().length());
				break;
		}
	}

	private OnClickListener	btnOnClickListener	= new OnClickListener()
										{
											@Override
											public void onClick(
													View v)
											{
												final int number = v
														.getId();
												new Thread()
												{
													Runnable	updateRunnable	= new Runnable()
																		{
																			@Override
																			public void run()
																			{
																				dealwithEnterCode(number);
																			}
																		};

													public void run()
													{
														_messageHandler
																.post(updateRunnable);
													}
												}.start();
											}
										};

	private void initInputBtn()
	{
		if (container_input == null)
			return;
		LinearLayout line1 = (LinearLayout) container_input.getChildAt(0);
		LinearLayout line2 = (LinearLayout) container_input.getChildAt(1);
		LinearLayout line3 = (LinearLayout) container_input.getChildAt(2);
		LinearLayout line4 = (LinearLayout) container_input.getChildAt(3);
		Button btn1 = (Button) line1.findViewById(R.id.btn_one);
		Button btn2 = (Button) line1.findViewById(R.id.btn_two);
		Button btn3 = (Button) line1.findViewById(R.id.btn_three);
		Button btn4 = (Button) line2.findViewById(R.id.btn_four);
		Button btn5 = (Button) line2.findViewById(R.id.btn_five);
		Button btn6 = (Button) line2.findViewById(R.id.btn_six);
		Button btn7 = (Button) line3.findViewById(R.id.btn_seven);
		Button btn8 = (Button) line3.findViewById(R.id.btn_eight);
		Button btn9 = (Button) line3.findViewById(R.id.btn_nine);
		Button btnOK = (Button) line4.findViewById(R.id.btn_ok);
		Button btn0 = (Button) line4.findViewById(R.id.btn_zero);
		Button btnDel = (Button) line4.findViewById(R.id.btn_delete);
		btn1.setId(1);
		btn2.setId(2);
		btn3.setId(3);
		btn4.setId(4);
		btn5.setId(5);
		btn6.setId(6);
		btn7.setId(7);
		btn8.setId(8);
		btn9.setId(9);
		btnOK.setId(10);
		btn0.setId(0);
		btnDel.setId(-1);
		btn1.setOnClickListener(btnOnClickListener);
		btn2.setOnClickListener(btnOnClickListener);
		btn3.setOnClickListener(btnOnClickListener);
		btn4.setOnClickListener(btnOnClickListener);
		btn5.setOnClickListener(btnOnClickListener);
		btn6.setOnClickListener(btnOnClickListener);
		btn7.setOnClickListener(btnOnClickListener);
		btn8.setOnClickListener(btnOnClickListener);
		btn9.setOnClickListener(btnOnClickListener);
		btnOK.setOnClickListener(btnOnClickListener);
		btn0.setOnClickListener(btnOnClickListener);
		btnDel.setOnClickListener(btnOnClickListener);
	}

	private void initInputMethod()
	{
		if (container_input == null)
		{
			container_input = (LinearLayout) ((ViewStub) findViewById(R.id.stub_inputMethod))
					.inflate();
			initInputBtn();
		}
		anim_down = AnimationUtils.loadAnimation(this, R.anim.push_down);

		anim_down.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				container_input.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}

			@Override
			public void onAnimationStart(Animation animation)
			{
				StockGroup.tabHost.getTabWidget().setVisibility(View.GONE);
				if (_iconTip != null)
				{
					_iconTip.setVisibility(View.GONE);
				}
			}
		});

		anim_up = AnimationUtils.loadAnimation(this, R.anim.push_up);

		anim_up.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				container_input.setVisibility(View.GONE);
				StockGroup.tabHost.getTabWidget().setVisibility(
						View.VISIBLE);
				if (_iconTip != null)
				{
					_iconTip.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}

			@Override
			public void onAnimationStart(Animation animation)
			{
			}
		});

		editTextView = (TextView) findViewById(R.id.editTextView);
		editTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (container_input == null)
				{
					container_input = (LinearLayout) ((ViewStub) findViewById(R.id.stub_import))
							.inflate();
					initInputBtn();
				}
				if (container_input.getVisibility() == View.VISIBLE)
				{
					return;
				}
				TDStockLog.d(TAG, "ready to hide tab widget");
				/*
				 * _current_stock_code.setFocusable(true);
				 * _current_stock_code.setFocusableInTouchMode(true);
				 */

				lastStockCode = _current_stock_code.getText().toString();

				_current_stock_code.setText("");
				_current_stock_code.requestFocus();
				container_input.startAnimation(anim_down);
				TDStockLog.d(TAG, "ready to show soft-keyboard!");
			}
		});
	}

	private static String	lastStockCode					= "1";
	// ////////////////////////by ouyangzhihui
	// 2011-7-8//////////////////////////////////
	private OnClickListener	onTouchInputMethodOnClickListener	= new OnClickListener()
													{
														@Override
														public void onClick(
																View v)
														{
															if (container_input != null)
															{
																if (container_input
																		.getVisibility() != View.GONE)
																{
																	container_input
																			.startAnimation(anim_up);
																	_current_stock_code
																			.setText(lastStockCode);
																	// _current_stock_code.setSelection(_current_stock_code.getText().toString().length());
																	_current_stock_code
																			.clearFocus();
																}
															}
															if (!isPause)
																loadDataUpdateUI(); // get data update ui
														}
													};

	@Override
	protected void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		TDStockLog.d(TAG, TAG + " onCreate");

		setCurrentStockCode();

		setContentView(R.layout.bmp_currentstockinfo);

		// "期指Futures"，"上証SSEI" set Adapter
		initFuturesAndSSEIAdapterType();

		initInputMethod(); // by ouyangzhihui 2011-7-8

		initRes4Replacement(); // next last stock

		_formaterOnSacle2 = DecimalFormat.getInstance();
		_formaterOnSacle2.setMaximumFractionDigits(2);
		_formaterOnSacle2.setMinimumFractionDigits(2);

		_formaterOnSacle1 = DecimalFormat.getInstance();
		_formaterOnSacle1.setMaximumFractionDigits(1);
		_formaterOnSacle1.setMinimumFractionDigits(1);

		Button _toolbutton_news = (Button) findViewById(R.id.toolbutton_bullets);
		Button _toolbutton_wc = (Button) findViewById(R.id.toolbutton_wc);
		Button _toolbutton_search = (Button) findViewById(R.id.toolbutton_search);
		Button _toolbutton_addstock = (Button) findViewById(R.id.toolbutton_addstock);
		_toolbutton_backWarrantResult = (Button) findViewById(R.id.toolbutton_backWarrantResult);

		_toolbutton_news.setFocusable(true);
		_toolbutton_news.setClickable(true);
		_toolbutton_wc.setFocusable(true);
		_toolbutton_wc.setClickable(true);

		_toolbutton_news.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				/*
				 * String stockCode = _current_stock_code.getText().toString();
				 * CurrentStockNewsListActivity._stockCode = stockCode;
				 * CurrentStockNewsListActivity._isComeFromBack = false; Intent
				 * intent = new Intent(getApplicationContext(),
				 * CurrentStockNewsListActivity.class);
				 * intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
				 * Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				 * 
				 * SwitchForwardActivity(CurrentStockNewsListActivity.class,
				 * intent);
				 */

				// modified by haibo in 2012-02-03 for new version
				String stockCode = _current_stock_code.getText().toString();
				NewStockNewsActivity._stockCode = stockCode;
				Intent intent = new Intent(getApplicationContext(),
						NewStockNewsActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(NewStockNewsActivity.class, intent);

			}
		});

		_toolbutton_wc.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				WarrantCBBCActivity.currStockCode = ((ITDLApplication) getApplicationContext())
						.getCurrentStockCode();
				WarrantCBBCActivity.currStockName = ((ITDLApplication) getApplicationContext())
						.getCurrentStockName();
				Intent intent = new Intent(getApplicationContext(),
						WarrantCBBCActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(WarrantCBBCActivity.class, intent);
			}
		});

		_toolbutton_search.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(getApplicationContext(),
						StockSearchActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(StockSearchActivity.class, intent);
			}
		});

		_toolbutton_addstock
				.setOnClickListener(new AddStockClickHandler(this));

		_toolbutton_backWarrantResult
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						SearchWarrantActivity.isFromActivityStockInfo = true;
						Intent intent = new Intent(
								getApplicationContext(),
								SearchWarrantActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
								| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
						SwitchForwardActivity(
								SearchWarrantActivity.class, intent);
					}
				});

		findViewById(R.id.toolbutton_stockstar).setOnClickListener(
				new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						String userName = ((ITDLApplication) getApplicationContext())
								.getUserName("");
						CommonDefn.ModeType iModeType = ((ITDLApplication) getApplicationContext())
								.getModeType();
						if (CommonDefn.ModeType.DELARY == iModeType
								&& CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY
										.equals(userName))
						{
							new CustomizeDialog(
									getMyOwnContext(),
									getResources().getString(
											R.string.info),
									getResources()
											.getString(
													R.string.realtime_info_msg),
									getResources().getString(
											R.string.ok)).show();
							return;
						}

						if (MoreGroup.group == null)
						{
							MoreGroup.forceToGoToRelatingTab();
						}
						StockStarIndexActivity.iFromClass = BMPCurrentStockInfoActivity.class;
						SwitchTabHostActivity(
								4,
								MoreGroup.GetActivityGroupHostControl(),
								StockStarIndexActivity.class);
					}
				});

		// by zhengan
		// Button _toolbutton_soccer = (Button)
		// findViewById(R.id.toolbutton_soccer);// 足球
		// Button _toolbutton_horserace = (Button)
		// findViewById(R.id.toolbutton_horserace);// 赛马
		//
		// _toolbutton_soccer.setOnClickListener(
		// new View.OnClickListener()
		// {
		// @Override
		// public void onClick(View v)
		// {
		// forwardToSoccerActivity();
		// }
		// });
		//
		// _toolbutton_horserace.setOnClickListener(
		// new View.OnClickListener()
		// {
		// @Override
		// public void onClick(View v)
		// {
		// forwardToHorseraceActivity();
		// }
		// });

		_stkTimeView = (StkTimeView) ((ViewGroup) findViewById(R.id.chart_container))
				.getChildAt(0);
		if (_stkTimeView == null)
		{
			TDStockLog.e(TAG, "can't find _stkTimeView!");
		}

		_chart_mask = (TextView) findViewById(R.id.chart_mask);
		// _chart_mask.setOnClickListener(new ChartClickHandler(this));

		_index_hsi = (TextView) findViewById(R.id.index_hsi_value);
		_index_his_net = (TextView) findViewById(R.id.index_hsi_net);
		_index_his_turnover = (TextView) findViewById(R.id.index_hsi_turn_over);

		_index_phsi = (TextView) findViewById(R.id.index_hscei_value);
		_index_phsi_net = (TextView) findViewById(R.id.index_hscei_net);

		_index_futures_hsi_1 = (TextView) findViewById(R.id.index_futures_hsi_1_value);
		_index_futures_hsi_1_net = (TextView) findViewById(R.id.index_futures_hsi_1_net);

		_index_futures_hsi_2 = (TextView) findViewById(R.id.index_futures_hsi_2_value);
		_index_futures_hsi_2_net = (TextView) findViewById(R.id.index_futures_hsi_2_net);

		_worldindex_sse1 = (TextView) findViewById(R.id.worldindex_sse1_value);
		_worldindex_sse1_net = (TextView) findViewById(R.id.worldindex_sse1_net);

		_server_time = (TextView) findViewById(R.id.server_timestamp);

		_current_stock_code = (EditText) findViewById(R.id.current_stock_code);
		_current_stock_code.setText(_stockCode);

		_current_stock_code.setClickable(true);
		_current_stock_code.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				_current_stock_code.setText("");
			}
		});

		_current_stock_code.setOnTouchListener(new OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				v.setTag(1);
				return false;
			}
		});

		_current_stock_code
				.setOnFocusChangeListener(new OnFocusChangeListener()
				{
					@Override
					public void onFocusChange(View v, boolean hasFocus)
					{
						if (hasFocus && v.getTag() != null
								&& v.getTag().equals(1))
						{
							_current_stock_code.setText("");
						}
						else
						{
							v.setTag(-1);
						}
					}
				});

		// Andy Testing
		// Mark to get the event done
		_current_stock_code.setImeOptions(EditorInfo.IME_ACTION_DONE);
		_current_stock_code
				.setOnEditorActionListener(new TextView.OnEditorActionListener()
				{
					@Override
					public boolean onEditorAction(TextView v,
							int actionId, KeyEvent event)
					{
						if (actionId == EditorInfo.IME_ACTION_DONE)
						{
							// Close Keybaord
							Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
							InputMethodManager imm = (InputMethodManager) service;
							imm.hideSoftInputFromWindow(
									_current_stock_code
											.getWindowToken(), 0);
							_current_stock_code.clearFocus();

							// If there is no network, create a prompt
							if (!SystemInfo
									.isNetworkingConnected(BMPCurrentStockInfoActivity.this))
								new CustomizeDialog(
										getMyOwnContext(),
										getResources().getString(
												R.string.info),
										getResources()
												.getString(
														R.string.networking_disconnect_tips))
										.show();
							else
							{
								_toolbutton_backWarrantResult
										.setVisibility(View.GONE);
								dealWithNewStockCodeComingFromEditor();
							}
							return true;
						}
						return false;
					}
				});

		_current_stock_chinese_short_name = (TextView) findViewById(R.id.current_stock_chinese_name);
		_current_stock_nominal = (TextView) findViewById(R.id.current_stock_nominal);

		_up_down = (ImageView) findViewById(R.id.current_stock_up_down_img);
		_current_stock_net = (TextView) findViewById(R.id.current_stock_net);
		_current_stock_net_percentage = (TextView) findViewById(R.id.current_stock_net_percentage);

		_current_stock_sharetraded = (TextView) findViewById(R.id.current_stock_sharetraded);
		_current_stock_turnover = (TextView) findViewById(R.id.current_stock_turnover);
		_current_stock_prevcloseprice = (TextView) findViewById(R.id.current_stock_prevcloseprice);
		_current_stock_openprice = (TextView) findViewById(R.id.current_stock_openprice);
		_current_stock_highprice = (TextView) findViewById(R.id.current_stock_highprice);
		_current_stock_lowprice = (TextView) findViewById(R.id.current_stock_lowprice);

		_rowForWarrant = (TableRow) findViewById(R.id.for_warrant_row);

		_current_stock_lotsize = (TextView) findViewById(R.id.current_stock_lotsize);
		_current_stock_ex_ymd = (TextView) findViewById(R.id.current_stock_ex_ymd);
		_current_stock_year_high = (TextView) findViewById(R.id.current_stock_year_high);
		_current_stock_div_ymd = (TextView) findViewById(R.id.current_stock_div_ymd);

		_current_stock_year_low = (TextView) findViewById(R.id.current_stock_year_low);
		_current_stock_div_value = (TextView) findViewById(R.id.current_stock_div_value);
		_current_stock_profitpershare = (TextView) findViewById(R.id.current_stock_profitpershare);
		_current_stock_rate_of_return = (TextView) findViewById(R.id.current_stock_rate_of_return);

		_current_stock_pe = (TextView) findViewById(R.id.current_stock_pe);
		_current_stock_currency = (TextView) findViewById(R.id.current_stock_currency);
		_current_stock_day_10_avg = (TextView) findViewById(R.id.current_stock_day_10_avg);

		_current_stock_rsi9 = (TextView) findViewById(R.id.current_stock_rsi9);
		_current_stock_day_20_avg = (TextView) findViewById(R.id.current_stock_day_20_avg);
		_current_stock_rsi14 = (TextView) findViewById(R.id.current_stock_rsi14);
		_current_stock_day_50_avg = (TextView) findViewById(R.id.current_stock_day_50_avg);

		{
			_current_stock_day_100_avg = (TextView) findViewById(R.id.current_stock_day_100_avg);
			_current_stock_day_200_avg = (TextView) findViewById(R.id.current_stock_day_200_avg);
			_current_stock_day_250_avg = (TextView) findViewById(R.id.current_stock_day_250_avg);
		}

		// modify by zor(ouyangzhihui) -start
		ImageView _img_logo = (ImageView) findViewById(R.id.img_logo);
		_img_logo.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent it = new Intent(BMPCurrentStockInfoActivity.this,
						AboutActivity.class);
				it.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				startActivityForResult(it, Activity.RESULT_OK);
			}
		});
		// modify by zor(ouyangzhihui) -start
		_scrollview = (ScrollView) findViewById(R.id.scrollview01);
		_scrollview.setScrollbarFadingEnabled(true);
		// 处理软键盘
		_scrollview.setOnClickListener(onTouchInputMethodOnClickListener);
		ViewGroup viewGroup_container = (ViewGroup) _scrollview.getChildAt(0);
		for (int i = 0; i < viewGroup_container.getChildCount(); i++)
		{
			viewGroup_container.getChildAt(i).setOnClickListener(
					onTouchInputMethodOnClickListener);
		}

		// Set up link for the Trading App
		setlinkToTrading();

		WebViewHelper.showAd(this, (WebView) findViewById(R.id.webView));

		isChangeModeType = false;
	}

	public static boolean	isChangeModeType	= false;

	/*-----------------by ouyangzhihui 2011-08-24-------------------*/
	private void initFuturesAndSSEIAdapterType()
	{
		/*----"期指Futures","上証SSEI"， delay - label add "*"-- by ouyangzhihui 2011-08-26---*/
		if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.ACCOUNTLOGIN
				&& !((ITDLApplication) getApplicationContext())
						.getIsRealtimeFutures())
		{
			TextView index_futures_label = (TextView) findViewById(R.id.index_futures_label);
			TextView next_month_label = (TextView) findViewById(R.id.next_month_label);
			index_futures_label.setText(index_futures_label.getText()
					.toString() + "*");
			next_month_label.setText(next_month_label.getText().toString()
					+ "*");
		}
		if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.ACCOUNTLOGIN
				&& !((ITDLApplication) getApplicationContext())
						.getIsRealtimeSSEI())
		{
			TextView index_sse1_label = (TextView) findViewById(R.id.index_sse1_label);
			index_sse1_label.setText(index_sse1_label.getText().toString()
					+ "*");
		}
		/*----"期指Futures","上証SSEI"， delay - label add "*"-- by ouyangzhihui 2011-08-26---*/
	}

	/*-----------------by ouyangzhihui 2011-08-24-------------------*/

	private void setCurrentStockCode()
	{
		_prefsStockCode = getSharedPreferences(
				CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		String stockCode = "1";
		if (_prefsStockCode != null)
		{
			stockCode = _prefsStockCode.getString(
					CommonDefn.PREFERENCE_STOCK_CODE, "1");
			if ("".equals(stockCode))
				stockCode = "1"; // modify by ouyangzhihui 2011-06-01
			if (TextUtils.isDigitsOnly(stockCode))
			{
				stockCode = Integer.toString(Integer
						.parseInt(stockCode, 10));
			}
			else
			{
				stockCode = "1";
			}
			_stockCode = stockCode;
			((ITDLApplication) this.getApplication())
					.setCurrentStockCode(_stockCode);
			TDStockLog.d(TAG, "ready to draw chart");
		}
	}

	protected void initRes4Replacement()
	{
		_res4ReplaceMent = new String[2][6];
		_res4ReplaceMent[0][0] = getResources().getString(
				R.string.short_name_ex_ymd);
		_res4ReplaceMent[0][2] = getResources().getString(
				R.string.short_name_div_value);
		_res4ReplaceMent[0][1] = getResources().getString(
				R.string.short_name_div_ymd);
		_res4ReplaceMent[0][3] = getResources().getString(
				R.string.short_name_rate_of_return);
		_res4ReplaceMent[0][4] = getResources().getString(
				R.string.short_name_profitpershare);
		_res4ReplaceMent[0][5] = getResources().getString(
				R.string.short_name_pe);

		_res4ReplaceMent[1][0] = getResources().getString(
				R.string.exchange_ratio);
		_res4ReplaceMent[1][1] = getResources().getString(R.string.exp_date);
		_res4ReplaceMent[1][2] = getResources()
				.getString(R.string.exer_price);
		_res4ReplaceMent[1][3] = getResources()
				.getString(R.string.call_price);
		_res4ReplaceMent[1][4] = getResources().getString(R.string.premium);
		_res4ReplaceMent[1][5] = getResources().getString(
				R.string.percent_out);

		_label4ReplaceMent = new TextView[6];

		_label4ReplaceMent[0] = (TextView) findViewById(R.id.replacement_label_01);
		_label4ReplaceMent[1] = (TextView) findViewById(R.id.replacement_label_02);
		_label4ReplaceMent[2] = (TextView) findViewById(R.id.replacement_label_03);
		_label4ReplaceMent[3] = (TextView) findViewById(R.id.replacement_label_04);
		_label4ReplaceMent[4] = (TextView) findViewById(R.id.replacement_label_05);
		_label4ReplaceMent[5] = (TextView) findViewById(R.id.replacement_label_06);

		_field_value_4ReplaceMent = new TextView[6];
		_field_value_4ReplaceMent[0] = (TextView) findViewById(R.id.current_stock_ex_ymd);
		_field_value_4ReplaceMent[1] = (TextView) findViewById(R.id.current_stock_div_ymd);
		_field_value_4ReplaceMent[2] = (TextView) findViewById(R.id.current_stock_div_value);
		_field_value_4ReplaceMent[3] = (TextView) findViewById(R.id.current_stock_rate_of_return);
		_field_value_4ReplaceMent[4] = (TextView) findViewById(R.id.current_stock_profitpershare);
		_field_value_4ReplaceMent[5] = (TextView) findViewById(R.id.current_stock_pe);

		_field_current_stock_call_put = (TextView) findViewById(R.id.current_stock_call_put);
		_field_current_stock_gearing = (TextView) findViewById(R.id.current_stock_gearing);

	}

	// @Override
	// public void onConfigurationChanged(Configuration newConfig)
	// {
	// forwardToChartActivity();
	//
	// super.onConfigurationChanged(newConfig);
	// }

	private void forwardToNvChart()
	{
		Intent intent = new Intent(getApplicationContext(),
				StkChartActivity.class);

		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
				| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		intent.putExtra(FinalKey.ITEMCODE, _stockCode);
		TDStockLog.i(TAG, "_stockCode=" + _stockCode);
		SwitchActivityFromHost(StkChartActivity.class, intent);
	}

	public synchronized void updateIndex(Index bundle)
	{
		String index_name = bundle.getName();
		String value = bundle.getLast();
		String net = bundle.getNet();
		// String netPrecentage = bundle.getNetPercentage();
		String turnover = bundle.getVol();

		// Log.d(TAG, "name=" + index_name + " , value=" + value + " , net=" +
		// net + " , turnover=" + turnover + " , " + netPrecentage);

		if (index_name == null || value == null || net == null/*
															 * || turnover ==
															 * null
															 */)
			return;

		if (index_name.equals(index_itemCode[1])) // 國企
		{
			boolean isNegative = net.indexOf("-") >= 0;
			try
			{
				_index_phsi.setText(StringUtils.formatScaleInteger(Double
						.parseDouble(value)));
			}
			catch (NumberFormatException e)
			{
				_index_phsi.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
			}
			net = StringUtils.formatToFiveCharsRule(net);

			_index_phsi_net.setText(StringUtils.formatString(net,
					isNegative ? null : "+", null));
			_index_phsi_net.setTextColor(isNegative ? Color.RED
					: Color.GREEN);
		}
		else if (index_name.equals(index_itemCode[0])) // 恆指
		{
			boolean isNegative = net.indexOf("-") >= 0;

			try
			{
				_index_hsi.setText(StringUtils.formatScaleInteger(Double
						.parseDouble(value)));

				String netStr = StringUtils.formatString(net,
						isNegative ? null : "+", null);
				netStr = StringUtils.formatToFiveCharsRule(netStr);

				String netPrecentage = StringUtils
						.formatRoundUpByNetPercetageNumber(Double
								.parseDouble(bundle.getNet())
								/ Double.parseDouble(bundle.getPrev())
								* 100);
				// StringUtils.
				netPrecentage = StringUtils.formatNumberByNetPerectage(
						netPrecentage, 4);
				_index_his_net
						.setText(netStr + "  (" + netPrecentage + ")");

				_index_his_net
						.setTextColor(net.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
			catch (Exception e1)
			{
				_index_hsi.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
				_index_his_net.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
				e1.printStackTrace();
			}

			try
			{
				_index_his_turnover
						.setText(StringUtils.formatNumberByUsingTruncate(
								_formaterOnSacle2,
								Double.parseDouble(turnover) / 100000000.00d,
								2)
								+ getResources().getString(
										R.string.a_hundred_million));
			}
			catch (Exception e)
			{
				_index_his_turnover
						.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
			}
		}
	}

	public synchronized void updateIndex_Futures(Futures futures/*
																 * String
																 * itemName,
																 * String value,
																 * String net
																 */)
	{
		if (futures == null || futures.getName() == null
				|| futures.getLast() == null)
			return;

		String value = futures.getLast();
		String net = futures.getNet();

		if (futures.getName().equals(futures_itemCode[0]))
		{
			try
			{
				_index_futures_hsi_1.setText(String.valueOf((int) Double
						.parseDouble(value)));
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_1.getText().toString().length() <= 0)
					_index_futures_hsi_1
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
			try
			{
				boolean isNegative = net.indexOf("-") >= 0;
				net = StringUtils.formatToFiveCharsRule(net);
				_index_futures_hsi_1_net.setText(StringUtils.formatString(
						net, isNegative ? null : "+", null));
				_index_futures_hsi_1_net
						.setTextColor(net.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_1_net.getText().toString().length() <= 0)
					_index_futures_hsi_1_net
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
		}
		else if (futures.getName().equals(futures_itemCode[1]))
		{
			try
			{
				_index_futures_hsi_2.setText(String.valueOf((int) Double
						.parseDouble(value)));
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_2.getText().toString().length() <= 0)
					_index_futures_hsi_2
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
			try
			{
				boolean isNegative = net.indexOf("-") >= 0;
				net = StringUtils.formatToFiveCharsRule(net);
				_index_futures_hsi_2_net.setText(StringUtils.formatString(
						net, isNegative ? null : "+", null));
				_index_futures_hsi_2_net
						.setTextColor(net.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_2_net.getText().toString().length() <= 0)
					_index_futures_hsi_2_net
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
		}
	}

	public synchronized void updateWorldIndex(String value, String net)
	{
		if (value == null || net == null)
			return;
		boolean isNegative = net.indexOf("-") >= 0;
		_worldindex_sse1.setText(StringUtils.formatScaleInteger(Double
				.parseDouble(value)));
		net = StringUtils.formatToFiveCharsRule(net);

		_worldindex_sse1_net.setText(StringUtils.formatString(net,
				isNegative ? null : "+", null));
		_worldindex_sse1_net.setTextColor(isNegative ? Color.RED
				: Color.GREEN);
	}

	public synchronized void syncServerTimer(String time)
	{
		if (time != null && !"".equals(time))
		{
			_server_time.setText(time.length() >= 8 ? time.subSequence(0, 8)
					: time);
		}
	}

	/**
	 * @param strDate
	 *            such as: 20071011 Style such as: YYYYMMdd
	 * @param newStyle
	 *            such as: yy/MM/dd
	 * @return such as: 2007-10-11
	 */
	private String resetDateFormat(String strDate)
	{
		String result = strDate;
		if (strDate != null && strDate.length() >= 8)
		{
			String year = strDate.substring(0, 4);
			String month = strDate.substring(4, 6);
			String day = strDate.substring(6, 8);
			// Log.d("yymmdd",String.format("%s/%s/%s",year,month,day));
			result = String
					.format("%s/%s/%s", year.substring(2), month, day);
		}
		return result;
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
	{
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.isCanceled())
		{
			if (_stockCode != null
					&& _stockCode.length() >= 1
					&& _current_stock_code.getText().toString().length() < 1)
				_current_stock_code.setText(_stockCode);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _current_stock_code.postInvalidate();
			_current_stock_code.clearFocus();
		}
		return false;
	}

	private class AddStockClickHandler extends DefaultClickHandler
	{
		public AddStockClickHandler(Context context)
		{
			super(context);
		}

		@Override
		protected void onDefaultAction()
		{
			if (container_input != null)
			{
				if (container_input.getVisibility() != View.GONE)
				{
					new CustomizeDialog(getMyOwnContext(), "", "請先按鍵確認股號!")
							.show();
					return;
				}
			}

			String stockCode = _current_stock_code.getText().toString();
			if (stockCode.length() < 1)
			{
				if (_stockCode.length() < 1)
				{
					return;
				}
				else
					stockCode = _stockCode;
			}
/*			DBHelper dbHelper = new DBHelper(
					BMPCurrentStockInfoActivity.this);
			try
			{*/
				/*
				 * int customerId = 1; //延迟模式
				 * if(((ITDLApplication)getApplicationContext
				 * ()).getModeType()==CommonDefn.ModeType.DELARY){ if
				 * (dbHelper.isSubscribeItemExist(customerId, stockCode,
				 * StockInfo.ADAPTER)) { new CustomizeDialog(getMyOwnContext(),
				 * "",
				 * getResources().getString(R.string.monitor_exist_stock)).show
				 * (); } else if (dbHelper.isFullWithItemInMonitor(customerId))
				 * { new CustomizeDialog(getMyOwnContext(), "",
				 * getResources().getString
				 * (R.string.monitor_is_full_with_items)).show(); } else if
				 * (dbHelper.isFullWithItemInMonitorBMPStock(customerId)) { new
				 * CustomizeDialog(getMyOwnContext(), "",
				 * getResources().getString
				 * (R.string.monitor_is_full_with_items_bmp_stock)).show(); }
				 * else { long result = dbHelper.insertSubscribeItem(customerId,
				 * stockCode, StockInfo.ADAPTER, StockInfo.STOCKCHISHORTNAME,
				 * StockInfo.NOMINAL, StockInfo.NET, StockInfo.NETPERCENTAGE);
				 * if (result > 0) { modify by zor(ouyangzhihui) String temp =
				 * _current_stock_chinese_short_name.getText().toString() + " "
				 * + stockCode; startAnimat(temp); }
				 * 
				 * TDStockLog.d(TAG, "insert result:" + result); } } //mode is
				 * not delay else{
				 * //if(MonitorUtil.getInstance().addBookMarkItem
				 * (stockCode,CommonDefn
				 * .BookMarkType.stock.getBookMarkType(),BMPCurrentStockInfoActivity
				 * .this)){ // _messageHandler.post(new
				 * SaveMonitor(_current_stock_chinese_short_name
				 * .getText().toString
				 * ()+" "+stockCode,MonitorUtil.items,BMPCurrentStockInfoActivity
				 * .this)); // }
				 * 
				 * 
				 * //}
				 */

/*			}
			catch (Exception e)
			{
				e.printStackTrace();
				TDStockLog.d(
						TAG,
						"insert result:" + e.getMessage() == null ? "unknown exception!"
								: e.getMessage());
			}
			finally
			{
				dbHelper.cleanup();
			}*/
			
			
			new SaveBookMarkAsyncTask(stockCode,
					CommonDefn.BookMarkType.stock.getBookMarkType(),
					BMPCurrentStockInfoActivity.this,
					MonitorUtil.getInstance(),
					_current_stock_chinese_short_name.getText()
							.toString() + " " + stockCode)
					.execute();
		}
	}

	private void dealWithNewStockCodeComingFromEditor()
	{
		_current_stock_nominal.setTag(null);

		String s = _current_stock_code.getText().toString().trim();
		if ("".equals(s) || Integer.parseInt(s) <= 0)
		{
			try
			{
				_entryErrordialog = new CustomizeDialog(getMyOwnContext(),
						"", getResources()
								.getString(R.string.entry_error))
				{
					@Override
					public void onClick(View v)
					{
						if (v == okButton)
						{
							dismiss();
							if (_stockCode != null
									&& _stockCode.length() >= 1)
							{
								_current_stock_code.setText(_stockCode);
								_current_stock_code.clearFocus();
							}
							Thread.yield();
							TDStockLog.d(TAG, " reset text !");
						}
					}
				};
				_entryErrordialog.show();
			}
			catch (Exception e)
			{
				TDStockLog.e(
						TAG,
						e.getMessage() == null ? "unknow exception happened when stock code is empty!"
								: "exception: " + e.getMessage());
			}
			return;
		}

		if (/* !s.equals(_stockCode) && */(!s.equals("")))
		{
			if (!s.toString().equals(_lastStockCode))
			{
				_lastStockCode = _stockCode;
				// _isNewStock = true;
			}

			try
			{
				_stockCode = String.valueOf(Integer.parseInt(s, 10));
				((ITDLApplication) getApplication())
						.setCurrentStockCode(_stockCode);
			}
			catch (NumberFormatException e1)
			{
				e1.printStackTrace();
				return;
			}
			_prefsStockCode = getSharedPreferences(
					CommonDefn.SYSTEM_CURRENT_SETTING,
					Context.MODE_PRIVATE);
			_prefsStockCode
					.edit()
					.putString(CommonDefn.PREFERENCE_STOCK_CODE,
							_stockCode).commit();

			loadDataUpdateUI(); // update data

			new Thread()
			{
				public void run()
				{
					_stkTimeView.drawImmediately();
				}
			}.start();
		}
	}

	private void dealwithNewStockCodeComingFromOtherPage(String newCode)
	{
		TDStockLog.d(TAG, "ready to deal with new stock code!");
		_current_stock_nominal.setTag(null);
		_lastStockCode = _current_stock_code.getText().toString();
		_current_stock_code.setText(newCode);

		_stockCode = newCode;
		((ITDLApplication) BMPCurrentStockInfoActivity.this.getApplication())
				.setCurrentStockCode(_stockCode);

		new Thread()
		{
			public void run()
			{
				_stkTimeView.drawImmediately();
			}
		}.start();

		try
		{
			try
			{
				Thread.sleep(500);
			}
			catch (InterruptedException e)
			{
			}
			loadDataUpdateUI("true");
		}
		catch (Exception e)
		{
			e.printStackTrace();
			TDStockLog.e(
					TAG,
					e.getMessage() == null ? " unknown exception happened!"
							: e.getMessage());
		}
	}

	private void resetFieldValue(boolean isWarrant, final Stock fromMsg)
	{
		if (!isWarrant)
		{
			try
			{
				_current_stock_ex_ymd.setText(resetDateFormat(fromMsg
						.getEx_ymd()));
			}
			catch (Exception e)
			{
				_current_stock_ex_ymd
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			} // --01

			try
			{
				_current_stock_div_ymd.setText(resetDateFormat(fromMsg
						.getDiv_ymd()));
			}
			catch (Exception e)
			{
				_current_stock_div_ymd
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			} // --02

			double nominal = 0.00d;
			try
			{
				nominal = Double.parseDouble(fromMsg.getNominal());
			}
			catch (Exception e)
			{
			}

			double divValue = 0.00d;
			try
			{
				divValue = Double.parseDouble(fromMsg.getDiv_value());
			}
			catch (Exception e)
			{
			}

			double dividendPaid = 0.00d;
			try
			{
				dividendPaid = Double.parseDouble(fromMsg
						.getDividend_paid());
			}
			catch (Exception e)
			{
			}

			try
			{
				/* // modify by zor(ouyangzhihui) 2011-08-12 --start */
				String tmp = Math.abs(divValue) <= 0.000001d ? CommonDefn.DEFAULT_FIELD_VALUE
						: String.valueOf(divValue);
				if (Double.parseDouble(tmp) < 100)
				{
					tmp = StringUtils.roundDownFormatToSixCharsRule(tmp)
							+ getResources().getString(R.string.cent);
				}
				else
				{
					tmp = String
							.valueOf(Double.parseDouble(tmp) / 100.00d);
					tmp = StringUtils.roundDownFormatToAutoCharsRule(tmp,
							2, true)
							+ getResources().getString(R.string.yuan);
				}
				/* // modify by zor(ouyangzhihui) 2011-08-12 --end */
				_current_stock_div_value.setText(tmp);
			}
			catch (Exception e)
			{
				_current_stock_div_value
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_div_value.postInvalidate(); // --03
			}

			try
			{
				_current_stock_rate_of_return
						.setText((Math.abs(dividendPaid) <= 0.000001d || Math
								.abs(nominal) <= 0.000001d) ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.roundDownFormatToSixCharsRule(dividendPaid
												/ nominal
												* 100
												+ ""));
			}
			catch (Exception e)
			{
				_current_stock_rate_of_return
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_rate_of_return.postInvalidate(); // --04
			}

			double profitpershare = 0.00d;
			try
			{
				profitpershare = Double.parseDouble(fromMsg
						.getProfit_per_share());
				// modify by zor(ouyangzhihui) 2011-08-12
				String profitPershareStr = Math.abs(profitpershare) <= 0.000001d ? CommonDefn.DEFAULT_FIELD_VALUE
						: StringUtils
								.roundDownFormatToSixCharsRule(String
										.valueOf(profitpershare));

				_current_stock_profitpershare.setText(profitPershareStr);
			}
			catch (Exception e)
			{
				_current_stock_profitpershare
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_profitpershare.postInvalidate(); // --05
			}

			String peStr = (Math.abs(profitpershare) <= 0.000001d || Math
					.abs(nominal) <= 0.000001d) ? CommonDefn.DEFAULT_FIELD_VALUE
					: String.valueOf((nominal / profitpershare));
			try
			{
				_current_stock_pe.setText(StringUtils
						.roundDownFormatToAutoCharsRule(peStr, 4, true));
			}
			catch (Exception e)
			{
				_current_stock_pe.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_pe.postInvalidate(); // --06
			}
		}
		else
		{

			try
			{
				_field_value_4ReplaceMent[0].setText(StringUtils
						.formatToDp(fromMsg.getRatio(), 3));
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[0]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[0].postInvalidate();
			}

			try
			{
				String expDate_src = fromMsg.getExp_date();
				String expDate_dest = expDate_src.substring(2, 4) + "/"
						+ expDate_src.substring(5, 7) + "/"
						+ expDate_src.substring(8, 10);
				_field_value_4ReplaceMent[1].setText(expDate_dest);
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[1]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[1].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[2].setText(fromMsg
						.getExer_price());
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[2]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[2].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[3].setText(fromMsg
						.getCall_price());
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[3]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[3].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[4].setText(fromMsg.getPremium());
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[4]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[4].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[5].setText(fromMsg
						.getPercent_out());
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[5]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[5].postInvalidate();
			}

			try
			{
				_field_current_stock_call_put.setText("P"
						.equalsIgnoreCase(fromMsg.getCallPut()) ? "Put輪"
						: "Call輪");
			}
			catch (Exception e)
			{
				_field_current_stock_call_put
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_current_stock_call_put.postInvalidate();
			}

			try
			{
				_field_current_stock_gearing.setText(fromMsg.getGearing());
			}
			catch (Exception e)
			{
				_field_current_stock_gearing
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_current_stock_gearing.postInvalidate();
			}
		}
	}

	private void resetLayoutByState(boolean isWarrant)
	{
		if (_isWarrant == isWarrant || _rowForWarrant == null)
		{
			return;
		}

		_isWarrant = isWarrant;
		if (isWarrant)
		{
			_rowForWarrant.setVisibility(View.VISIBLE);
			_label4ReplaceMent[0].setText(_res4ReplaceMent[1][0]);
			_label4ReplaceMent[1].setText(_res4ReplaceMent[1][1]);
			_label4ReplaceMent[2].setText(_res4ReplaceMent[1][2]);
			_label4ReplaceMent[3].setText(_res4ReplaceMent[1][3]);
			_label4ReplaceMent[4].setText(_res4ReplaceMent[1][4]);
			_label4ReplaceMent[5].setText(_res4ReplaceMent[1][5]);
		}
		else
		{
			_rowForWarrant.setVisibility(View.GONE);

			_label4ReplaceMent[0].setText(_res4ReplaceMent[0][0]);
			_label4ReplaceMent[1].setText(_res4ReplaceMent[0][1]);
			_label4ReplaceMent[2].setText(_res4ReplaceMent[0][2]);
			_label4ReplaceMent[3].setText(_res4ReplaceMent[0][3]);
			_label4ReplaceMent[4].setText(_res4ReplaceMent[0][4]);
			_label4ReplaceMent[5].setText(_res4ReplaceMent[0][5]);
		}
	}

	protected boolean forwardToChartActivity()
	{
		forwardToNvChart();

		return true;
	}

	protected synchronized void handleExitApplication()
	{
		new AlertDialog.Builder(this.getParent() == null ? this
				: this.getParent())
				.setTitle(getResources().getString(R.string.info))
				.setMessage(
						getResources().getString(
								R.string.application_exit_tips))
				.setIcon(getResources().getDrawable(
						R.drawable.help_menu_icon))
				.setPositiveButton(getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener()
						{
							public void onClick(
									DialogInterface dialoginterface,
									int i)
							{
								((ITDLApplication) getApplicationContext())
										.setExitApp(true);
								exitApp();
							}
						})
				.setNegativeButton(
						getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,
									int whichButton)
							{

							}
						}).show();

	}

	private void hightLightChangeItems(Object lastNominalValue,
			String nominalValue, String netValue)
	{
		double lastValue = CommonDefn.APPROACH_ZERO;
		double currentValue = 0.00d;
		double net_value = 0.00d;
		try
		{
			lastValue = Double.parseDouble(lastNominalValue == null ? "0.00"
					: lastNominalValue.toString());
			currentValue = Double.parseDouble(nominalValue);
			net_value = Double.parseDouble(netValue);

			TDStockLog.d(TAG, String.format(
					"last=%f, current=%f, netValue=%s", lastValue,
					currentValue, net_value));
		}
		catch (Exception e)
		{
			lastValue = 0.00d;
		}

		int color = CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_GREEN;
		if (lastNominalValue == null
				|| (Math.abs(lastValue - CommonDefn.APPROACH_ZERO) <= CommonDefn.APPROACH_ZERO))
		{
			color = (net_value >= 0.00d) ? CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_GREEN
					: CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_ORANGE;
		}
		else
		{
			color = (currentValue > lastValue) ? CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_GREEN
					: CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_ORANGE;
		}

		final int highlightColor = color;
		final Runnable changeBg = new Runnable()
		{
			@Override
			public void run()
			{
				_current_stock_nominal.setBackgroundColor(highlightColor);
				_current_stock_net.setBackgroundColor(highlightColor);
				_current_stock_net_percentage
						.setBackgroundColor(highlightColor);
				// modify by ouyangzhihui 2011-06-28
				_current_stock_net.setTextColor(Color.BLACK);
				_current_stock_net_percentage.setTextColor(Color.BLACK);
			}
		};

		final Runnable reStoreBg = new Runnable()
		{
			@Override
			public void run()
			{
				_current_stock_nominal.setBackgroundDrawable(null);
				_current_stock_net.setBackgroundDrawable(null);
				_current_stock_net_percentage.setBackgroundDrawable(null);
				// modify by ouyangzhihui 2011-06-28
				_current_stock_net
						.setTextColor(_current_stock_net.getText()
								.toString().indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
				_current_stock_net_percentage
						.setTextColor(_current_stock_net_percentage
								.getText().toString().indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
		};

		new Thread()
		{
			@Override
			public void run()
			{
				_messageHandler.post(changeBg);
				_messageHandler.postDelayed(reStoreBg, 1000);
			}
		}.start();
	}

	/*
	 * Update
	 */
	private void loadDataUpdateUI(String... isSunflower)
	{
		TDStockLog.i(TAG, "LOADING...");

		if (isSunflower.length > 0)
			super.SetShowProgressView(true);
		else
			super.SetShowProgressView(false);

		super.SendHttpRequest();

	}

	public void updateCurrentStockInfo(final Stock fromMsg)
	{
		TDStockLog.d(TAG, "exception NewStock=" + fromMsg.getSchi_name()
				+ " , " + fromMsg.getNominal() + " , " + fromMsg.getNet()
				+ " , " + fromMsg.getPrev_close_price());
		try
		{
			if (fromMsg == null)
			{
				try
				{
					String errMsg = "找不到此股號!";

					if (_entryErrordialog == null)
					{
						_entryErrordialog = new CustomizeDialog(
								getMyOwnContext(), "", errMsg)
						{
							@Override
							public void onClick(View v)
							{
								if (v == okButton)
								{
									dismiss();
									if (_lastStockCode != null
											&& _lastStockCode
													.length() >= 1)
									{
										// _isNewStock = false;
										_current_stock_code
												.setText(_lastStockCode);
										_current_stock_code
												.clearFocus();
									}
									// dealWithNewStockCodeComingFromEditor();
									Thread.yield();
									TDStockLog.d(TAG,
											" reset stock ocde here ?!");
								}
							}
						};
					}
					else
					{
						_entryErrordialog.setMsgContent(errMsg);
					}

					((Activity) BMPCurrentStockInfoActivity.this
							.getParent()).runOnUiThread(new Runnable()
					{
						public void run()
						{
							_entryErrordialog.show();
						}
					});
				}
				catch (Exception e)
				{
					TDStockLog.d(
							TAG,
							e.getMessage() == null ? "unknow exception happened when stock code is empty!"
									: "exception: " + e.getMessage());
				}

				return;
			}

			if ("0".equals(fromMsg.getStock_code())
					|| fromMsg.getStock_code() == null
					|| fromMsg.getNominal() == null)
			{
				return;
			}

			{
				String nature = (fromMsg.getNature() == null ? " nature= null"
						: fromMsg.getNature());

				// -------------deal with nature & warrantType-------------
				resetLayoutByState("W".equalsIgnoreCase(nature));
				resetFieldValue("W".equalsIgnoreCase(nature), fromMsg);
				// -------------deal with nature & warrantType-------------
			}

			try
			{
				// if (_current_stock_nominal.getTag() == null ||
				// !_current_stock_nominal.getTag().toString().equals(fromMsg.getNominal()))
				// {
				hightLightChangeItems(_current_stock_nominal.getTag(),
						fromMsg.getNominal(), fromMsg.getNet());
				// }
				_current_stock_nominal.setTag(fromMsg.getNominal());
			}
			catch (Exception e3)
			{
				e3.printStackTrace();
			}

			String net = fromMsg.getNet();
			String sharetraded = fromMsg.getShare_traded();
			String turnover = fromMsg.getTurnover();
			String prevcloseprice = fromMsg.getPrev_close_price();
			String openprice = fromMsg.getOpen_price();

			_current_stock_chinese_short_name
					.setText(fromMsg.getSchi_name());
			((ITDLApplication) getApplicationContext())
					.setCurrentStockName(fromMsg.getSchi_name());
			_current_stock_nominal.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.STOCKPRICE,
					fromMsg.getNominal()));
			boolean isDown = net.indexOf("-") >= 0;
			_up_down.setImageResource(net == null ? null
					: isDown ? R.drawable.down_24_1 : R.drawable.up_24_1);
			_current_stock_net.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.NET, net));
			int color = net == null ? Color.WHITE : isDown ? Color.RED
					: Color.GREEN;
			_current_stock_net.setTextColor(color);

			String netPrecentage = "";
			if (net != null && prevcloseprice != null)
			{
				try
				{
					if (Double.parseDouble(prevcloseprice) == 0d)
					{
						netPrecentage = "0";
					}
					else
					{
						netPrecentage = String.valueOf(Double
								.parseDouble(net)
								/ Double.parseDouble(prevcloseprice)
								* 100);
					}
				}
				catch (Exception e)
				{
					netPrecentage = "0";
				}

				TDStockLog.d(TAG, "NetPrecentage=" + netPrecentage);
			}

			_current_stock_net_percentage
					.setText((net == null || prevcloseprice == null) ? CommonDefn.DEFAULT_FIELD_VALUE
							: String.format(
									"(%s)",
									StringUtils
											.FormatNumber(
													StringUtils.ITDLNumber.NETPERCENTAGE,
													netPrecentage)));
			_current_stock_net_percentage.setTextColor(color);

			try
			{
				_current_stock_sharetraded
						.setText(sharetraded == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils.formatNumberByTurnove(
										String.valueOf(Double
												.parseDouble(sharetraded) / 1000.00d),
										1));
				_current_stock_turnover
						.setText(turnover == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: String.format(
										"$%s",
										StringUtils
												.formatNumberByTurnove(
														String.valueOf(Double
																.parseDouble(turnover) / 1000.00d),
														1)));

				_current_stock_prevcloseprice
						.setText(prevcloseprice == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.FormatNumber(
												StringUtils.ITDLNumber.STOCKPRICE,
												prevcloseprice));
				_current_stock_openprice
						.setText(openprice == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.FormatNumber(
												StringUtils.ITDLNumber.STOCKPRICE,
												openprice));
				_current_stock_highprice.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.STOCKPRICE,
						fromMsg.getHigh_price()));
				_current_stock_lowprice.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.STOCKPRICE,
						fromMsg.getLow_price()));
			}
			catch (NumberFormatException e2)
			{
				e2.printStackTrace();
			}

			_current_stock_lotsize.setText(fromMsg.getLot_size());
			try
			{
				_current_stock_year_high.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.HIGHTLOW,
						fromMsg.getYearHigh()));
			}
			catch (NumberFormatException e1)
			{
				e1.printStackTrace();
			}

			try
			{
				_current_stock_year_low.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.HIGHTLOW,
						fromMsg.getYearLow()));
			}
			catch (NumberFormatException e1)
			{
				e1.printStackTrace();
			}

			try
			{
				try
				{
					_current_stock_rsi9.setText(StringUtils.FormatNumber(
							StringUtils.ITDLNumber.STOCKPRICE,
							fromMsg.getRsi9()));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				try
				{
					_current_stock_rsi14.setText(StringUtils.FormatNumber(
							StringUtils.ITDLNumber.STOCKPRICE,
							fromMsg.getRsi14()));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				// by ouyangzhihui 2011-8-01
				try
				{
					_current_stock_currency
							.setText(fromMsg.getCurrency_code() == null ? CommonDefn.DEFAULT_FIELD_VALUE
									: fromMsg.getCurrency_code());
				}
				catch (Exception e)
				{
					_current_stock_currency
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				}

				try
				{
					_current_stock_day_10_avg.setText(StringUtils
							.formatToDp(fromMsg.getDay10avg(), 3));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_20_avg.setText(StringUtils
							.formatToDp(fromMsg.getDay20avg(), 3));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_50_avg.setText(StringUtils
							.formatToDp(fromMsg.getDay50avg(), 3));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_100_avg.setText(StringUtils
							.formatToDp(fromMsg.getDay100avg(), 3));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_200_avg.setText(StringUtils
							.formatToDp(fromMsg.getDay200avg(), 3));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_250_avg.setText(StringUtils
							.formatToDp(fromMsg.getDay250avg(), 3));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
			catch (Exception e)
			{
				TDStockLog.d(TAG, "exception=" + e.toString());
				e.printStackTrace();
			}
		}
		catch (Exception e)
		{
			TDStockLog.d(TAG, "exception=" + e.toString());
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume()
	{
		super.SetExectuHttpRequestOnResume(false);
		super.onResume();
		TDStockLog.d(TAG, TAG + " onResume");

		isPause = false;

		if (isChangeModeType)
		{
			// "期指Futures"，"上証SSEI" set Adapter
			initFuturesAndSSEIAdapterType();
			isChangeModeType = false;
		}

		// by ouyangzhihui 2011-06-15
		_toolbutton_backWarrantResult
				.setVisibility(SearchWarrantActivity.isNextActivityStockInfo ? View.VISIBLE
						: View.GONE);
		SearchWarrantActivity.isNextActivityStockInfo = false;

		((ITDLApplication) getApplication()).setTimeChartInBackground(false);

		String tmpCode = _prefsStockCode.getString(
				CommonDefn.PREFERENCE_STOCK_CODE, "1");
		dealwithNewStockCodeComingFromOtherPage(tmpCode);
		// loadDataUpdateUI(); // get data update ui
	}

	private boolean	isPause	= false;

	@Override
	protected void onPause()
	{
		super.onPause();
		TDStockLog.d(TAG, TAG + " onPause");

		isPause = true;
		_scrollview.performClick(); // 处理软键盘

		((ITDLApplication) getApplication()).setTimeChartInBackground(true);
	}

	@Override
	protected void onStart()
	{
		super.onStart();
		TDStockLog.d(TAG, TAG + " onStart");
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();
		TDStockLog.d(TAG, TAG + " onRestart");
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		TDStockLog.d(TAG, TAG + " onStop");
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		TDStockLog.d(TAG, TAG + " onDestroy");
	}

	@Override
	public void onBackPressed()
	{
		// super.onBackPressed();
		TDStockLog.d(TAG, this.getClass().getSimpleName() + " onBackPressed");

		if (container_input != null) // 處理軟鍵盤
		{
			if (container_input.getVisibility() != View.GONE)
			{
				_scrollview.performClick();
				// container_input.startAnimation(anim_up);
				// _current_stock_code.setText(lastStockCode);
				// _current_stock_code.setSelection(_current_stock_code.getText().toString().length());

				return;
			}
		}

		handleExitApplication();
	}

	private void setlinkToTrading()
	{
		if (TradeAppInfo.TradeApp_Ready == false)
			return;

		_chart_mask.setOnClickListener(tradeEnterListener);
	}

	private void PlaceSwitchTradeOrderKeyPad(
			Trade_StockViewInfoItem iStockInfo, String iOrderSide,
			String iPrice)
	{
		// When an OK is pressed, we will start the keypad with available
		// information
		Intent intentObj;

		Trade_StockReqOrderItem transferObj;

		intentObj = new Intent(actContext, Trade_OrderKeypadActivity.class);

		// Provide with no order no
		transferObj = new Trade_StockReqOrderItem("", iStockInfo.stockCode,
				iStockInfo.chnName, iStockInfo.engName);
		// The outstanding is the remaining quantity for order
		transferObj.SetOrderQuantity("0", "0", iStockInfo.stepVolume);

		// Assume it is a buy
		transferObj.SetOrderSide(iOrderSide);
		transferObj.SetOrderPrice(iPrice);
		transferObj.SetCurrencyCode(iStockInfo.currencyCode);
		transferObj.SetOrderType("E");

		// Place the Order info, then the Stock View Info
		intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo,
				transferObj);
		intentObj.putExtra(Trade_AppConstant.stockViewInfo, iStockInfo);

		TradeAppInfo.SetStockViewInfoItem(null);

		// Place the bundle object to the intent
		SwitchActivityFromHost(Trade_OrderKeypadActivity.class, intentObj);
	}

	private ProgressDialog	waitingDialog	= null;

	protected void ShowWaitingDialog()
	{
		if (waitingDialog == null)
		{
			waitingDialog = new ProgressDialog(getMyOwnContext());
			waitingDialog.setIndeterminate(true);
			waitingDialog.setCancelable(false);
		}
		waitingDialog.setMessage(getString(R.string.waitingText));
		waitingDialog.show();
	}

	private void DismissWaitingDialog()
	{
		if (waitingDialog == null)
			return;

		if (waitingDialog.isShowing())
			waitingDialog.dismiss();
	}

	private boolean		isGettingStockCode	= false;

	// The only way to get data is to download
	private OnClickListener	tradeEnterListener	= new OnClickListener()
										{
											@Override
											public void onClick(
													View iViewObj)
											{
												boolean isDemoOnly;

												if ((_stockCode == null)
														|| (_stockCode
																.length() == 0))
													return;

												if (isGettingStockCode == true)
													return;

												// Allow for testing environment
												isDemoOnly = TradeAppInfo
														.IsAllowDemoOnly(appHost
																.GetLSClient_ServicePlan());
												if (debugMode)
													TDStockLog.i(
															TAG,
															"TradeApp isDemoOnly: "
																	+ isDemoOnly);

												// If it is a demo account, it must be relogon
												Class<? extends Activity> primaryAct;
												String requestCode;

												primaryAct = appHost.actListController
														.GetCurrentActivityClass();
												// Set our primary return class
												TradeAppInfo
														.SetPrimaryEntryClass(primaryAct);
												TradeAppInfo
														.SetAsBMPMode(appHost
																.IsBMPMode());

												requestCode = Trade_StockFunctionTools
														.FormatFullStockCode(String
																.valueOf(_stockCode));

												TradeAppInfo
														.SetStockViewInfoItem(
																new Trade_StockViewInfoItem(
																		requestCode,
																		"",
																		""),
																Trade_StockReqOrderItem.TRANSACTIONTYPE_BID);

												/* Andy */
												// //Enfroce for BMP Mode
												// if (appHost.IsBMPMode())
												// {
												// TradeAppInfo.SetAsBMPMode(false);
												// isDemoOnly = true;
												// }

												if (isDemoOnly)
												{
													TradeAppInfo
															.SetAsDemoAccount(true);
													TradeAppInfo
															.SetTradingRegistration(false);
													SwitchActivityFromHost(Trade_LoginActivity.class);
													return;
												}

												// Provide a method for use to escape from Demo Mode
												if (TradeAppInfo
														.IsDemoAccount()
														|| !TradeAppInfo
																.IsTradingRegistered())
												{
													TradeAppInfo
															.SetAsDemoAccount(false);
													TradeAppInfo
															.SetTradingRegistration(false);
													SwitchActivityFromHost(Trade_LoginActivity.class);
													return;
												}

												// We can not obtain the info, so bring it back to option page
												if (IsNetworkAvailable() == false)
												{
													// Flush the data
													TradeAppInfo
															.SetStockViewInfoItem(null);
													SwitchActivityFromHost(Trade_tradingOptionActivity.class);
													return;
												}

												// We are performing a download
												final TradeGetDetailStockQuote quoteRequest;

												isGettingStockCode = true;
												ShowWaitingDialog();
												quoteRequest = new TradeGetDetailStockQuote(
														actContext);
												quoteRequest
														.SetRequestQuoteInfo(
																appHost.IsDevelopment(),
																requestCode,
																appHost.GetLSClient_AccountLogonName(),
																appHost.GetLSClient_SessionKey());
												quoteRequest
														.SendRequest(
																TradeAppInfo
																		.IsDemoAccount(),
																new ITradeGetStockQuoteResponse()
																{
																	@Override
																	public void ResponseFunc(
																			boolean iSuccessfulSend,
																			TradeGetStockQuoteResult iResponse)
																	{
																		isGettingStockCode = false;
																		DismissWaitingDialog();
																		quoteRequest
																				.Dispose();
																		if (iSuccessfulSend == false)
																		{
																			new CustomizeDialog(
																					getMyOwnContext(),
																					getString(R.string.info),
																					getString(R.string.commErrorText),
																					getString(R.string.ok))
																					.show();
																			return;
																		}

																		if (!iResponse.resultCode
																				.equals("0"))
																		{
																			if (iResponse.resultCode
																					.equals("-1"))
																				appHost.LS_Client_ResetConnection();

																			String textValue;

																			textValue = iResponse.errorMessage;
																			if (textValue
																					.equals(""))
																				textValue = getString(R.string.commErrorText);

																			new CustomizeDialog(
																					getMyOwnContext(),
																					getString(R.string.info),
																					textValue,
																					getString(R.string.ok))
																					.show();
																			return;
																		}
																		PlaceSwitchTradeOrderKeyPad(
																				iResponse.stockQuoteItem,
																				Trade_StockReqOrderItem.TRANSACTIONTYPE_BID,
																				iResponse.stockQuoteItem
																						.GetCurAskPriceText());
																	}
																});
												return;
											}
										};

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return StockGroup.GetActivityGroupHostControl();
	}

	@Override
	public void ScreenOrientation_Response(SCR_ORIENTATION orientation)
	{
		if ((orientation == SCR_ORIENTATION.LANDSCAPE))
		{
			forwardToChartActivity();
		}
	}

	@Override
	public void NetworkChange_Response(CONNECT_TYPE iConnect,
			NetworkInfo iNetInfo)
	{
		if (iNetInfo.isAvailable() || iNetInfo.isConnected())
		{
			WebViewHelper.showAd(this, (WebView) findViewById(R.id.webView));
		}
	}

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		return HttpAppInfo.SendBMPStockPageAllRequest(actContext, _stockCode,
				this);
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(
			H_UserClient_HttpRequest_Result iResult)
	{
		if (!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}
		updateData(iResult.objArrayStores);
	}

	private void updateData(Object[] objs)
	{
		if (objs == null)
			return;

		final Map<String, Index> indexList = (Map<String, Index>) objs[0];
		final Map<String, Futures> futuresList = (Map<String, Futures>) objs[1];
		final WorldIndex worldIndex = (WorldIndex) objs[2];
		final Stock stock = objs[3] != null ? (Stock) objs[3] : null;
		final String serverTime = objs[4].toString();

		TDStockLog.d(
				TAG,
				"OBJ=>" + indexList.size() + "," + futuresList.size() + ","
						+ worldIndex.getName() + ","
						+ stock.getSchi_name() + "," + serverTime);

		final Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					if (stock != null)
						updateCurrentStockInfo(stock);

					if (serverTime != null && serverTime.length() > 1)
					{
						// serverTime = serverTime.substring(8, 10) + ":" +
						// serverTime.substring(10, 12) + ":" +
						// serverTime.substring(12, 14);
						String iTmpServerTime = serverTime.substring(8,
								10)
								+ ":"
								+ serverTime.substring(10, 12)
								+ ":"
								+ serverTime.substring(12, 14);
						syncServerTimer(iTmpServerTime);
					}
				}
				catch (Exception e)
				{
					TDStockLog.d(TAG, "exception=" + e.toString());
				}
			}
		};
		try
		{
			new Thread()
			{
				@Override
				public void run()
				{
					_messageHandler.post(runnable);
				}
			}.start();

			final Runnable runnableIndex = new Runnable()
			{
				@Override
				public void run()
				{
					if (indexList != null)
					{
						for (int i = 0; i < indexList.size(); i++)
						{
							updateIndex(indexList.get(index_itemCode[i]));
						}
					}
					if (indexList != null)
					{
						for (int i = 0; i < futuresList.size(); i++)
						{
							updateIndex_Futures(futuresList
									.get(futures_itemCode[i]));
						}
					}
					if (worldIndex != null)
						updateWorldIndex(worldIndex.getLast(),
								worldIndex.getNet());
				}
			};

			new Thread()
			{
				@Override
				public void run()
				{
					_messageHandler.post(runnableIndex);
				}
			}.start();

		}
		catch (Exception e)
		{
			_messageHandler.post(runnable);
			e.printStackTrace();
		}
	}
}
